package com.usian.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.usian.CartFeign;
import com.usian.OrderFeign;
import com.usian.pojo.OrderInfo;
import com.usian.pojo.TbItem;
import com.usian.pojo.TbOrder;
import com.usian.pojo.TbOrderShipping;
import com.usian.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/frontend/order")
public class OrderController {

    @Autowired
    private CartFeign cartFeign;

    @Autowired
    private OrderFeign orderFeign;


    /**
     * 跳转到结算页 从购物车携带商品信息
     *
     * @param userId
     * @param token
     * @param ids
     * @return
     */
    @RequestMapping("goSettlement")
    public Result goSettlement(@RequestParam String userId,@RequestParam String token,@RequestParam String[] ids){

        Map<String, Object> map = cartFeign.getCartByUserId(userId);

        List<TbItem> list =new ArrayList<>();
        for(String id :ids){
            ObjectMapper objectMapper =new ObjectMapper();
            TbItem tbItem = objectMapper.convertValue(map.get(id), TbItem.class);
            list.add(tbItem);
        }

        if(list.size()>0){
            return Result.ok(list);
        }
         return Result.error("查无数据");
    }


    /**
     * 保存订单
     *
     * @param orderItem
     * @param tbOrder
     * @param tbOrderShipping
     * @return
     */
    @RequestMapping("insertOrder")
    public Result insertOrder(@RequestParam String orderItem,
                              TbOrder tbOrder,TbOrderShipping tbOrderShipping){

        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderItem(orderItem);
        orderInfo.setTbOrder(tbOrder);
        orderInfo.setTbOrderShipping(tbOrderShipping);
        long result = orderFeign.insertOrder(orderInfo);
        if(result >0){
            return Result.ok(result);
        }
        return Result.error("保存失败");
    }

    @RequestMapping("test")
    public String test(){
        System.out.println("!111111111111111111111");
        return "222";
    }
}
